package com.hzpd.hainan.module.usercenter.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.ViewUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import de.greenrobot.event.EventBus;
import com.hzpd.hainan.R;
import com.hzpd.hainan.config.CODE;
import com.hzpd.hainan.model.event.ChangeNameEvent;
import com.hzpd.hainan.model.news.NewsFlashEntity;
import com.hzpd.hainan.model.usercenter.UserEntity;
import com.hzpd.hainan.module.usercenter.UserCenterFragment;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.BM;
import com.hzpd.hainan.utils.DeviceUtils;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.SPUtil;
import com.hzpd.hainan.utils.TUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.google.common.base.Charsets.UTF_8;

public class ChangeNameOrSignDialog extends Dialog implements View.OnClickListener {

    @BindView(R.id.changname_edit)
    EditText changname_edit;
    @BindView(R.id.changename_title)
    TextView changename_title;
    TextView changename_confirm;
    TextView changename_cancel;

    private Activity activity;
    private View view;
    private SPUtil spu;

    private int type;

    public ChangeNameOrSignDialog(Context context) {
        super(context);
        activity = (Activity) context;
        spu = SPUtil.getInstance();

    }

    public ChangeNameOrSignDialog(Context context, int theme, int type) {
        super(context, theme);
        activity = (Activity) context;
        spu = SPUtil.getInstance();

        this.type = type;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        init();
    }


    private void init() {
        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        LogUtils.i("width-->" + width);
        view = LayoutInflater.from(activity).inflate(R.layout.dialog_changename, null);

        setContentView(view);
        changname_edit = (EditText) view.findViewById(R.id.changname_edit);
        changename_title = (TextView) view.findViewById(R.id.changename_title);
        changename_confirm = (TextView) view.findViewById(R.id.changename_confirm);
        changename_cancel = (TextView) view.findViewById(R.id.changename_cancel);

        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
            changename_cancel.setText("取消");
            changename_confirm.setText("确认");
        }else{
            changename_cancel.setText("ཕྱིར་འཐེན།");
            changename_confirm.setText("གཏན་འཁེལ།");
        }

        changename_cancel.setOnClickListener(this);
        changename_confirm.setOnClickListener(this);
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.END | Gravity.BOTTOM);
        lp.width = width;
        dialogWindow.setAttributes(lp);
        if (null != spu.getUser()) {
            if (type == 0) {
                if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
                    changename_title.setText("请输入昵称(最多8位)");
                }else{
                    changename_title.setText("མིང་འགོད་པ།  ཡིག་འབྲུ་བརྒྱད་ཀྱི་ཚད།");
                }
                changname_edit.setText(spu.getUser().getNickname());
            } else {
                changename_title.setText("请输入签名");
                changname_edit.setText(spu.getUser().getDesc());
            }
        }
    }

//	@OnClick({R.id.changename_confirm, R.id.changename_cancel})
//	public void click(View view) {
//		switch (view.getId()) {
//			case R.id.changename_confirm:
//				changeName();
//				break;
//			case R.id.changename_cancel:
//				dismiss();
//				break;
//			default:
//				break;
//		}
//	}

    public void changeName() {
        String str = changname_edit.getText().toString();
        if (null == str || "".equals(str)) {
            if (0 == type) {
                TUtils.toast("请输入新的昵称");
            } else {
                TUtils.toast("请输入新的签名");
            }
            return;
        }
        Map<String, String> map = new HashMap<>();
        if (0 == type) {
            map.put("nickname", str);
        } else {
            map.put("desc", str);
        }
        map.put("uid", spu.getUser().getUid());

        Factory.provideHttpService()
                .changeUser(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        if ("200".equals(userEntity.code)) {
                            LogUtils.e("nickname---"+spu.getUser().getNickname());
                            spu.setUser(userEntity.data);
                            Intent intent = new Intent();
                            intent.setAction(UserCenterFragment.ACTION_USER);
                            activity.sendBroadcast(intent);
                            dismiss();
                            return true;
                        } else {
                            TUtils.toast(userEntity.msg);
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity entity) {


                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                        LogUtils.i("200-->失败"+throwable.toString());
                    }
                });


    }
    public void changeName1() {
        String str=null;
        String str1 = changname_edit.getText().toString();
        BM bm=new BM();
        try {
             str=bm.toGBK(str1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (null == str || "".equals(str)) {
            if (0 == type) {
                TUtils.toast("请输入新的昵称");
            } else {
                TUtils.toast("请输入新的签名");
            }
            return;
        }
        Map<String, String> map = new HashMap<>();
        if (0 == type) {
            map.put("nickname", str);
        } else {
            map.put("desc", str);
        }
        map.put("uid", spu.getUser().getUid());
        LogUtils.e("nickName", spu.getUser().getNickname());
        Factory.provideHttpService()
                .changeUser(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<UserEntity, Boolean>() {
                    @Override
                    public Boolean call(UserEntity userEntity) {
                        LogUtils.e("nickName", userEntity.code);

                        return true;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<UserEntity>() {
                    @Override
                    public void call(UserEntity userEntity) {
                        dismiss();
                        if ("200".equals(userEntity.code)) {
                            TUtils.toast("修改成功");
                            LogUtils.e("nickName", userEntity.data.getNickname());
                            spu.setUser(userEntity.data);
                            LogUtils.e("nickName", userEntity.data.getNickname());
                            Intent intent = new Intent();
                            intent.setAction(UserCenterFragment.ACTION_USER);
                            activity.sendBroadcast(intent);


                        } else {
                            TUtils.toast(userEntity.msg);
                        }


                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.changename_confirm:
                LogUtils.e("nickName", "修改昵称");
                changeName();
                break;
            case R.id.changename_cancel:
                dismiss();
                break;
            default:
                break;
        }
    }

	@Override
	public void dismiss() {
		super.dismiss();
		ChangeNameEvent event = new ChangeNameEvent();
		event.setNameChange(true);
		EventBus.getDefault().post(event);
	}

}